package edu.cibertec.sicsolutions.vfs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import edu.cibertec.sicsolutions.constants.SessionConstants;
import edu.cibertec.sicsolutions.vfs.domain.votacion.ElectorVirtual;

/**
 * This Filter class handle the security of the application.
 * <p>
 * It should be configured inside the web.xml.
 * 
 */
public class SecurityElectorFilter implements Filter {
	// the login page uri
	private static final String LOGIN_PAGE_ELECTOR = "/index2.jsp";

	// the logger object
	private static final Logger log = Logger
			.getLogger(SecurityElectorFilter.class);

	public void init(FilterConfig arg0) throws ServletException {
	}

	/**
	 * Standard doFilter object.
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		log.debug("doFilter");

		String requestUri = ((HttpServletRequest) req).getRequestURI();
		if(StringUtils.contains(requestUri, "loginElector.do") ||
				StringUtils.contains(requestUri, "votacion.do")){ 
			if (!StringUtils.contains(requestUri, "loginElector.do")&& !authorize((HttpServletRequest) req)) {
				log.debug("authorization failed");
				((HttpServletRequest) req).setAttribute("msj",
						"Sus sesion ha expirado");
				((HttpServletRequest) req).getRequestDispatcher(LOGIN_PAGE_ELECTOR).forward(req, res);
			} else {
				log.debug("authorization succeeded");
				chain.doFilter(req, res);
			}	
		}
		else{
			chain.doFilter(req, res);
		}
	}

	public void destroy() {
	}

	private boolean authorize(HttpServletRequest req) {
		log.info("begin method authorize");
		boolean succeed = false;
		ElectorVirtual electorVirtual = (ElectorVirtual) req.getSession()
				.getAttribute(SessionConstants.ELECTOR);
		try {
			if (electorVirtual != null) {
				log.info("authorization to Elector : "+ electorVirtual.getLogin());
				succeed = true;
			}
			else{
				req.getSession().setAttribute("msjLogin", "Su sesion ha expirado.Vuelva a ingresar");	
			}
		} catch (Exception e) {
			log.error(null, e);
		}
		log.info("begin method authorize");
		return succeed;
	}

}
